package com.itheima.reggie.controller;

import com.itheima.reggie.common.OssTemplate;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

/**
 * 文件上传和下载
 */
@RestController
@Slf4j
@RequestMapping("/common")

public class CommonController {
    //浏览器上传
    @Autowired
    private OssTemplate ossTemplate;
//    @PostMapping("/upload")
//    public R<String> upload(@RequestBody MultipartFile file) throws IOException {
//        String originalFilename = file.getOriginalFilename();
//        String upload = ossTemplate.upload(file.getOriginalFilename(), file.getInputStream());
//        return R.success(upload);
//    }
//
//    @GetMapping("/download")
//    public void download(HttpServletResponse response,String name) throws IOException {
//        //获取网络文件并转为输入流
//        //输入流，通过输入流读取文件内容
//        //https:/reggie-65.oss-cn-nanjing.aliyuncs.com/images/2022/11/20/47ee4584-888d-4dd1-9e45-6cb0d19ac9e5.jpg
//        boolean contains = name.contains("https");
//        if(!contains){
//            name="https://reggie-65.oss-cn-nanjing.aliyuncs.com/images/"+name;
//        }
//
//        HttpURLConnection httpUrl = (HttpURLConnection) new URL(name).openConnection();
//        httpUrl.connect();
//        InputStream inputStream = httpUrl.getInputStream();
//        //输出流，通过输出流将文件写回浏览器
//        ServletOutputStream outputStream = response.getOutputStream();
//        int len = 0;
//        byte[] bytes = new byte[1024];
//        while ((len = inputStream.read(bytes)) != -1){
//            outputStream.write(bytes,0,len);
//            outputStream.flush();
//        }
//        //关闭资源
//        outputStream.close();
//        inputStream.close();
//    }


}
